package com.example.systemserver.service;

import cn.hutool.core.util.IdUtil;
import com.example.systemserver.bean.RequestBean;
import com.example.systemserver.bean.StudentBean;
import com.example.systemserver.config.MyException;
import com.example.systemserver.dao.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;

    public void save(StudentBean studentBean) {
        log.debug("学员信息保存,检查参数完整度");
        if (studentBean == null){
            throw new MyException("参数错误"); // 抛出异常 停止程序 返回异常信息
        }
        if (studentBean.getTitle() == null|| studentBean.getTitle().trim().isEmpty()){
            throw new MyException("姓名不能为空");
        }
        if (studentBean.getAge() == null || studentBean.getAge() <= 0) {
            throw new MyException("年龄不能小于0");
        }
        if (studentBean.getGender() == null || studentBean.getGender().trim().isEmpty()||studentBean.getGender().length()>1){
           throw new MyException("性别格式错误");
        }

        log.debug("学员信息保存, 判断新增/更新");
        if (studentBean.getId()==null){
            log.debug("新增，补充参数");
            studentBean.setId(IdUtil.getSnowflakeNextId());
            studentBean.setCreatedTime(System.currentTimeMillis());
            studentBean.setUpdatedTime(System.currentTimeMillis());

            log.debug("新增，执行操作");
            int updated = studentMapper.save(studentBean);  //异常
            if (updated<=0){
               throw new MyException("保存失败");
            }
        }else{
            log.debug("更新，补充参数");
            studentBean.setUpdatedTime(System.currentTimeMillis());
            log.debug("更新，执行操作");
            int updated = studentMapper.update(studentBean);
            if (updated<=0){
                throw new MyException("更新失败");
            }
        }
    }

    public PageInfo<StudentBean> list(RequestBean requestBean){
        log.debug("查询列表,设置分页");
        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize(),requestBean.getOrderBy());
        log.debug("查询列表,执行操作");
        StudentBean params = requestBean.getParams();

        List<StudentBean> list = studentMapper.list(params);

        return PageInfo.of( list);
    }

    public void updated() {
        System.out.println("更新数据");
    }

    public boolean remove(StudentBean studentBean) {
        int updated = studentMapper.remove(studentBean);
        return updated > 0;
    }

    public StudentBean info(StudentBean studentBean) {
        StudentBean info = studentMapper.info(studentBean);
        return info;
    }

}
